from datetime import datetime, timedelta
from utils.config import DEFAULT_REMINDER_MINUTES
import re

def calculate_reminder_time(event_time, minutes_before=30):
    """
    计算提醒时间（比事件提前指定分钟）
    支持多种时间格式输入
    """
    # 标准化时间格式
    if isinstance(event_time, str):
        # 尝试解析常见格式
        formats = [
            "%Y-%m-%d %H:%M",
            "%Y-%m-%d",
            "%m/%d/%Y %H:%M",
            "%m/%d/%Y"
        ]
        for fmt in formats:
            try:
                dt = datetime.strptime(event_time, fmt)
                break
            except ValueError:
                continue
        else:
            raise ValueError("Invalid time format. Use YYYY-MM-DD HH:MM or similar")
    else:
        dt = event_time
    
    # 计算提醒时间
    reminder = dt - timedelta(minutes=minutes_before)
    
    # 返回标准格式
    return reminder.strftime("%Y-%m-%d %H:%M")

def format_time(time_str, show_seconds=False):
    """
    格式化时间显示（用于UI）
    - 显示为"HH:MM" 或 "HH:MM:SS"
    - 处理数据库时间格式
    """
    if not time_str:
        return "N/A"
    
    # 处理数据库格式 (YYYY-MM-DD HH:MM:SS)
    if re.match(r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}", time_str):
        dt = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")
    # 处理其他格式
    elif re.match(r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}", time_str):
        dt = datetime.strptime(time_str, "%Y-%m-%d %H:%M")
    else:
        try:
            dt = datetime.strptime(time_str, "%Y-%m-%d")
        except:
            return time_str
    
    # 格式化输出
    if show_seconds:
        return dt.strftime("%H:%M:%S")
    return dt.strftime("%H:%M")

def is_within_reminder_window(event_time, minutes=30):
    """检查当前时间是否在提醒窗口内"""
    event_dt = datetime.strptime(event_time, "%Y-%m-%d %H:%M")
    reminder_time = event_dt - timedelta(minutes=minutes)
    now = datetime.now()
    
    return reminder_time <= now <= event_dt

def calculate_next_recurring_date(current_date, recurring_type, end_date=None):
    """计算重复事件的下一次日期（支持每日/每周/每月）"""
    current = datetime.strptime(current_date, "%Y-%m-%d")
    
    if recurring_type == "daily":
        next_date = current + timedelta(days=1)
    elif recurring_type == "weekly":
        next_date = current + timedelta(weeks=1)
    elif recurring_type == "monthly":
        next_date = current.replace(month=current.month % 12 + 1)
        if next_date.month == 1:
            next_date = next_date.replace(year=current.year + 1)
    else:
        return None
    
    # 检查结束日期
    if end_date and next_date > datetime.strptime(end_date, "%Y-%m-%d"):
        return None
        
    return next_date.strftime("%Y-%m-%d")